package com.xincongjun.media.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.List;

public class FileUtil {

    public static final Logger logger = LoggerFactory.getLogger(FileUtil.class);

    public static String getFileExtension(String fileName) {
        int dotIndex = fileName.lastIndexOf('.');
        return (dotIndex > 0 && dotIndex < fileName.length() - 1)
                ? fileName.substring(dotIndex + 1).toLowerCase()
                : "";
    }

    public static String getRealFileType(String filePath) throws Exception {
        ProcessBuilder getExtBuilder = new ProcessBuilder("exiftool", "-File:FileTypeExtension", filePath);
        Process getExtProcess = getExtBuilder.start();

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(getExtProcess.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.contains("File Type Extension")) {
                    int colonIndex = line.indexOf(":");
                    if (colonIndex != -1 && colonIndex + 1 < line.length()) {
                        return line.substring(colonIndex + 1).trim().toLowerCase();
                    }
                }
            }
        }
        getExtProcess.waitFor();
        return null;
    }

    public static String getFileName(String fileName) {
        int dotIndex = fileName.lastIndexOf('.');
        return (dotIndex > 0) ? fileName.substring(0, dotIndex) : fileName;
    }

    public static void swapFileNames(String firstFilePath, String secondFilePath) {
        File firstFile = new File(firstFilePath);
        File secondFile = new File(secondFilePath);

        if (!firstFile.exists()) {
            logger.error("第一个文件不存在：{}", firstFilePath);
            return;
        }
        if (!secondFile.exists()) {
            logger.error("第二个文件不存在：{}", secondFilePath);
            return;
        }

        String firstFileName = getFileName(firstFile.getName());
        String firstFileExt = getFileExtension(firstFile.getName());

        String secondFileName = getFileName(secondFile.getName());
        String secondFileExt = getFileExtension(secondFile.getName());

        File tempFile = new File(firstFile.getParent(), "__temp_swap_file__." + firstFileExt);

        try {
            if (!firstFile.renameTo(tempFile)) {
                logger.error("无法将第一个文件重命名为临时文件：{}", tempFile.getAbsolutePath());
                return;
            }

            File secondToFirst = new File(secondFile.getParent(), firstFileName + "." + secondFileExt);
            if (!secondFile.renameTo(secondToFirst)) {
                logger.error("无法将第二个文件重命名为：{}", secondToFirst.getAbsolutePath());
                tempFile.renameTo(firstFile);
                return;
            }

            File tempToSecond = new File(firstFile.getParent(), secondFileName + "." + firstFileExt);
            if (!tempFile.renameTo(tempToSecond)) {
                logger.error("无法将临时文件重命名为：{}", tempToSecond.getAbsolutePath());
                secondToFirst.renameTo(secondFile);
                tempFile.renameTo(firstFile);
                return;
            }

        } catch (Exception e) {
            throw new RuntimeException("交换文件名失败: " + firstFilePath + " " + secondFilePath, e);
        } finally {
            if (tempFile.exists()) {
                tempFile.delete();
            }
        }
    }

    public static String generateRandomSixDigitNumberString() {
        int number = (int) (Math.random() * 900000) + 100000;
        return String.valueOf(number);
    }

    public static void renameFile(String filePath, String prefix, String infix, String suffix, String separator) {
        File originalFile = new File(filePath);
        String originalName = originalFile.getName();
        String extension = FileUtil.getFileExtension(originalName);

        List<String> parts = new ArrayList<>();
        if (prefix != null && !prefix.isEmpty()) {
            parts.add(prefix);
        }
        if (infix != null && !infix.isEmpty()) {
            parts.add(infix);
        }
        if (suffix != null && !suffix.isEmpty()) {
            parts.add(suffix);
        }
        String baseName = String.join(separator, parts);
        String newName = baseName + "." + extension;

        File parentDir = originalFile.getParentFile();
        File newFile = new File(parentDir, newName);

        try {
            Files.move(originalFile.toPath(), newFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        } catch (Exception e) {
            throw new RuntimeException("文件重命名失败：" + filePath, e);
        }
    }

    public static void moveFile(String oldFilePath, String newFilePath) {
        Path sourcePath = new File(oldFilePath).toPath();
        Path targetPath = new File(newFilePath).toPath();

        try {
            Files.move(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
        } catch (Exception e) {
            throw new RuntimeException("移动文件失败：" + oldFilePath, e);
        }
    }

    public static void moveFileToDirectory(String oldFilePath, String targetDirectoryPath) {
        File sourceFile = new File(oldFilePath);
        File targetDir = new File(targetDirectoryPath);

        File targetFile = new File(targetDir, sourceFile.getName());

        try {
            Files.move(sourceFile.toPath(), targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        } catch (Exception e) {
            throw new RuntimeException("移动文件失败：" + oldFilePath + " -> " + targetFile.getAbsolutePath(), e);
        }
    }

    public static void deleteDirectory(File directory) {
        if (directory.exists()) {
            File[] files = directory.listFiles();

            if (files != null) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        deleteDirectory(file);
                    } else {
                        file.delete();
                    }
                }
            }

            directory.delete();
        }
    }



}
